package com.imdada.open.platform.client.order;

import com.imdada.open.platform.client.internal.req.order.AddOrderReq;
import com.imdada.open.platform.client.internal.resp.order.AddOrderResp;
import com.imdada.open.platform.config.Configuration;
import com.imdada.open.platform.exception.RpcException;
import com.imdada.open.platform.util.AddOrderUtils;
import com.imdada.open.platform.util.ApiUtils;
import com.imdada.open.platform.util.OrderNoGenerator;
import lombok.extern.slf4j.Slf4j;

import java.util.Collections;
import java.util.Map;

/**
 * 订单预发布代码示例(接口文档地址：http://newopen.imdada.cn/#/development/file/readyAdd)
 */
@Slf4j
public class QueryDeliverFeeAndAddOrderClient {

    /**
     * 查询订单运费接口URL
     */
    private static final String QUERY_DELIVER_FEE_URL = Configuration.getInstance().getHost() + "/api/order/queryDeliverFee";
    /**
     * 查询运费后发单接口URL
     */
    private static final String ADD_AFTER_QUERY_URL = Configuration.getInstance().getHost() + "/api/order/addAfterQuery";

    public static AddOrderResp execute() throws RpcException {
        // 生成一个三方单号
        String orderNo = OrderNoGenerator.generateOrderNo();
        return execute(orderNo);
    }

    /**
     * 订单预发布
     */
    public static AddOrderResp execute(String orderNo) throws RpcException {
        // 1. 查询运费
        AddOrderResp addOrderResp = queryDeliverFee(orderNo);

        // 2. 查询运费后发单
        addAfterQuery(addOrderResp.getDeliveryNo());

        return addOrderResp;
    }

    /**
     * 查询运费
     * @return
     * @throws Exception
     */
    private static AddOrderResp queryDeliverFee(String orderNo) throws RpcException {
        // 构建基本信息
        AddOrderReq body = AddOrderUtils.buildOrderDetail4Demo(orderNo);

        // 执行请求
        String rpcResult = ApiUtils.callApiWithBizParam(QUERY_DELIVER_FEE_URL, body);

        // 处理结果
        return AddOrderUtils.parseAddOrderResponse(rpcResult, "调用达达查询运费接口失败");
    }

    private static void addAfterQuery(String deliveryNo) throws RpcException {
        log.info("查询运费后发单，deliveryNo: {}", deliveryNo);

        // 构建基本信息
        Map<String, String> body = Collections.singletonMap("deliveryNo", deliveryNo);

        // 执行请求
        ApiUtils.callApiWithBizParamAndLogResponse(ADD_AFTER_QUERY_URL, body);
    }

}
